<?php

class Engine_Controller_Plugin_Routes extends Zend_Controller_Plugin_Abstract {

	
	public function __construct(Array $options = array())
    {
		$this->init($options);
    }

    public function init(array $options) {
    }
    
    
    public function routeShutdown($request) {
    	if (!$this->resolveHome($request))
    		$this->resolveMobile($request);
    }
    
    
    public function resolveMobile(&$request) {
    	$result = false;
    	$moduleName = $this->getRequest()->getModuleName();
    	if ($moduleName != 'mobile') {
    		$mobile = new Zend_Session_Namespace('Mobile');
    		if ($mobile->isMobile) {
    			if (!isset($mobile->useFullWebsite)) {
    				$result = true;
    			} else {
    				if (!$mobile->useFullWebsite) {
    					$result = true;
    				}
    			}
    		}
    	}
    	
    	if ($result) {
			$this->getResponse()->clearBody();
			$this->getResponse()->clearHeaders();
			$this->getResponse()->setHttpResponseCode(302); 
			$this->getResponse()->setRedirect(Zend_Registry::get('baseUrl').'/mobile');
       	}
    	return $result;
    }
    
    
    /**
     * 
	 * In an effort to remove duplicate content by allowing multiple URLs to display the
	 * same URL content, we prepare this function to reroute to a single home URL.  The
	 * callung function should return a 301 HTTP code if this function returns true.
	 * 
     * @param unknown_type $request
     */
    protected function resolveHome(&$request) {
    	
    	/**
    	 *  If the user attempts to visit the home URL with one of the following stems
    	 *     -  /default
    	 *     -  /default/index.php
    	 *     -  /index
    	 *     -  /index/index.php
    	 *     -  /index.php
    	 *
    	 *	then the URL is rerouted to / via an HTTP 301 Status code.
    	 */
    	$result = false;
    	if (isset($_SERVER["REDIRECT_URL"])) {
			$rurl = $_SERVER["REDIRECT_URL"];
			if (strlen($rurl) > 1) {
				$rurl = rtrim($rurl, '/');
			}
			if (($rurl == '/index') || ($rurl == '/default') || ($rurl == '/index.php') ||
			    ($rurl == '/index/index.php') || ($rurl == '/default/index.php')) {
				$result = true;
			}
    	} else {
    		// If there is no REDIRECT_URL then it is /index.php directly called
    		$result = true;
    	}
			
		if ($result) {
			$this->getResponse()->clearBody();
			$this->getResponse()->clearHeaders();
			$this->getResponse()->setHttpResponseCode(301); 
			$this->getResponse()->setRedirect(Zend_Registry::get('baseUrl'));
		}
		return $result;
    }
}
?>